package com.yc.testThread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class CustomThread {
	
	/**
	 * 内置固定线程的线程池newFixedThreadPool
	 * submit有返回值，要配合Callable任务
	 * execute没有返回值，配合runable
	 */
	public void m() {
		ExecutorService executorService = Executors.newFixedThreadPool(3);
		
//		submit动态判断lamdba如果有返回值，就认为是Callable，如果没有返回值就认为是Runnable
		Future<Object> submitResult = executorService.submit(() -> {//public <T> Future<T> submit(Callable<T> task)
			System.out.println("--------do something1");
			throw new RuntimeException("Exception1");
//			return new Object();
		});
		
		executorService.submit(() -> {//public Future<?> submit(Runnable task)
			System.out.println("--------do something1");
		});
		
		executorService.submit(new myRunnable());//public Future<?> submit(Runnable task)
		executorService.submit(new myCallable());//public <T> Future<T> submit(Callable<T> task)
		
//		try {
//			System.out.println(submitResult.get());
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (ExecutionException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		executorService.execute(() -> {
			System.out.println("--------do something2");
			throw new RuntimeException("Exception2");
		});
		executorService.shutdown();
	}
	
	/**
	 * 自定义线程池
	 */
	public void m1() {
		ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 20, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
		ThreadPoolExecutor tpe2 = new ThreadPoolExecutor(5, 20, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new myHandler());
		
	}
	
	/**
	 * 自定义线程超出队列承载之后的丢弃策略
	 * 默认四种：丢弃并抛异常、静默丢弃、丢弃队列头任务、直接执行
	 * @author yuancan
	 *
	 */
	class myHandler implements RejectedExecutionHandler {

		@Override
		public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
			
			
		}
		
	}
	
	/**
	 * 自定义线程名称：需要通过自定义线程工厂来实现
	 * @author yuancan
	 *
	 */
	class myFactory implements ThreadFactory {

		@Override
		public Thread newThread(Runnable r) {
			// TODO Auto-generated method stub
			return null;
		}
		
	}
	
	class myCallable implements Callable<String> {

		@Override
		public String call() throws Exception {
			System.out.println("-------------");
			return "success";
		}
	}
	
	class myRunnable implements Runnable {
		@Override
		public void run() {
			
			
		}
	}
	

	public static void main(String[] args) {
		CustomThread ct = new CustomThread();
		ct.m();

	}

}
